﻿using System;

namespace MusicPlow
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MusicPlowRESTApi" in code, svc and config file together.
    public class MusicPlowRESTApi : IMusicPlowRESTApi
    {
        public SearchResults FromFreeText(string text, string amountStr)
        {
            int amount;
            if (!int.TryParse(amountStr, out amount))
            {
                amount = 5;
            }

            DateTime startTime = DateTime.Now;
            SearchResults retValue;
            
            try
            {
                var entireFlowTask = MainFlow.FreetextFlow(text, amount);
                entireFlowTask.Wait();
                retValue = entireFlowTask.Result;
            }
            catch
            {
                retValue = new SearchResults();
            }

            retValue.DurationInMS = (DateTime.Now - startTime).TotalMilliseconds;
            return retValue;
        }

        public SearchResults FromYoutubeVideo(string videoid, string amountStr)
        {
            int amount;
            if (!int.TryParse(amountStr, out amount))
            {
                amount = 5;
            }
            
            DateTime startTime = DateTime.Now;
            SearchResults retValue;
            
            try
            {
                var topTask = Youtube.GetTitle(videoid).
                    ContinueWith<SearchResults>(t => 
                        {
                            if (string.IsNullOrWhiteSpace(t.Result.Result))
                            {
                                return new SearchResults();
                            }
                            else
                            {
                                var entireFlowTask = MainFlow.FreetextFlow(t.Result.Result, amount);
                                entireFlowTask.Wait();
                                return entireFlowTask.Result;
                            }
                        });
                topTask.Wait();
                retValue = topTask.Result;
            }
            catch
            {
                retValue = new SearchResults();
            }

            retValue.DurationInMS = (DateTime.Now - startTime).TotalMilliseconds;
            return retValue;
        }
    }
}
